package com.ht.WeNas.rest_controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.ht.WeNas.utils.exceptions.MessageException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLConnection;

@Tag(name = "图片控制器")
@RestController
@RequestMapping("/api/img")
@Slf4j
public class ImageController {
    @GetMapping
    @Operation(summary = "获取图片")
    public void getImage(
            @Parameter(description = "文件路径") @RequestParam("path") String path,

            @Parameter(description = "最大图片宽度")
            @RequestParam(value = "maxWidth", required = false)
            String maxWidth,

            HttpServletResponse response
    ) {
        Integer w = null;
        if (StrUtil.isNotBlank(maxWidth) && NumberUtil.isNumber(maxWidth)) {
            try {
                w = Integer.valueOf(maxWidth);
            } catch (NumberFormatException e) {
                throw new MessageException("图片宽度参数错误");
            }
        }
        response.addHeader("Cache-Control", "public");
        response.addHeader("Content-Type", URLConnection.guessContentTypeFromName(path));
        try (ServletOutputStream os = response.getOutputStream()) {
            if (w != null) {
                Thumbnails.Builder<File> builder = Thumbnails.of(path);
                builder.size(w, Integer.MAX_VALUE);
                builder.toOutputStream(os);
            } else {
                IoUtil.copy(FileUtil.getInputStream(path), os);
            }
        } catch (IOException e) {
            log.warn("IO异常", e);
            throw new MessageException("IO异常");
        } catch (Exception e) {
            log.warn("图片处理失败，请检查传入参数", e);
            throw new MessageException("图片处理失败，请检查传入参数");
        }
    }

    @GetMapping("/base64")
    @Operation(summary = "获取图片")
    public String getImageAsBase64(
            @Parameter(description = "文件路径") @RequestParam("path") String path,

            @Parameter(description = "最大图片宽度")
            @RequestParam(value = "maxWidth", required = false)
            String maxWidth
    ) {
        Integer w = null;
        if (StrUtil.isNotBlank(maxWidth) && NumberUtil.isNumber(maxWidth)) {
            try {
                w = Integer.valueOf(maxWidth);
            } catch (NumberFormatException e) {
                throw new MessageException("图片宽度参数错误");
            }
        }
        try {
            if (w != null) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                Thumbnails.Builder<File> builder = Thumbnails.of(path);
                builder.size(w, Integer.MAX_VALUE);
                builder.toOutputStream(os);
                return Base64Encoder.encode(os.toByteArray());
            } else {
                byte[] bytes = FileUtil.getInputStream(path).readAllBytes();
                return Base64Encoder.encode(bytes);
            }
        } catch (IOException e) {
            log.warn("IO异常", e);
            throw new MessageException("IO异常");
        } catch (Exception e) {
            log.warn("图片处理失败，请检查传入参数", e);
            throw new MessageException("图片处理失败，请检查传入参数");
        }
    }
}
